package com.stack;

/**
 * @program: letcode
 * @author: lin
 * @create: 2020-03-17 17:06
 * @description: 使用数组实现顺序栈
 */
public class MyStack {

    int[] elements;

    int length;

    public MyStack(){
        elements = new int[0];
    }

    // 数据进栈
    public void push(int element){

        /**
         * 这里为什么要创建一个新的数组来保存添加数据：
         *     1.因为数组的容量在初始化时就固定好的，不能动态扩容
         */
        int[] newArr = new int[elements.length+1];
        for (int i = 0; i < elements.length; i++) {
            newArr[i] = elements[i];
        }

        newArr[elements.length] = element;
        elements = newArr;

    }

    // 数据出栈
    public int pop(){

        if(elements.length == 0){
            System.out.println("栈内没有数据了");
        }

        int element = elements[elements.length - 1];


        int[] newArr = new int[elements.length - 1];

        for (int i = 0; i < elements.length - 1; i++) {
            newArr[i] = elements[i];
        }

        elements = newArr;

        return element;
    }

    // 查看栈顶元素
    public int peek() {
        //栈中没有元素
        if(elements.length==0) {
            throw new RuntimeException("stack is empty");
        }
        return elements[elements.length-1];
    }

    // 判断栈是否为空
    public boolean isEmpty() {
        return elements.length==0;
    }


    public static void main(String[] args) {
        MyStack myStack = new MyStack();
        myStack.push(4);
        System.out.println("查看栈顶："+myStack.peek());
        myStack.push(5);
        myStack.push(1);
        myStack.push(9);
        System.out.println(myStack.pop());
        System.out.println(myStack.pop());
        //查看栈顶元素
		System.out.println(myStack.peek());
        System.out.println(myStack.isEmpty());
    }

}
